package com.sunxueqi.common.utils;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Value;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class AddressUtils {

//	@Value("${tecentKey}")
//	private static String key;
	
	public static void main(String[] args) {
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("ip", "112.64.60.54");
		paramMap.put("accessKey", "alibaba-inc");
		String str = HttpRequest.get(IP_URL).form(paramMap).execute().body();
		System.out.println(str);
		JSONObject jsonObj = JSONUtil.parseObj(str);
		
		String address ="";
		// 国家
		String nation = (String) JSONUtil.getByPath(jsonObj, "data.country");
		// 省
		String province = (String) JSONUtil.getByPath(jsonObj, "data.city");
		// 市
		String city = (String) JSONUtil.getByPath(jsonObj, "data.region");
		// 区
		String district = (String) JSONUtil.getByPath(jsonObj, "result.ad_info.district");
		// 行政区划代码
		//String adcode = JSONUtil.getByPath(jsonObj, "result.ad_info.adcode").toString();
		address = nation + province + city + district;
		System.out.println(address);
	}
	
	// 阿里ip查询接口
	public static final String IP_URL = "http://ip.taobao.com/outGetIpInfo";
	
	/**
	 * 根据ip获取对应的城市信息
	 * @param ip
	 * @return
	 */
	public static String getCityInfoByIp(String ip) {
		if(IpUtils.internalIp(ip)) {
			return "内网IP";
		}
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("ip", ip);
		paramMap.put("accessKey", "alibaba-inc");
		String str = HttpRequest.get(IP_URL).form(paramMap).execute().body();
		
		JSONObject jsonObj = JSONUtil.parseObj(str);
		
		/**
		 * 	
		 * 	状态码，0为正常,
			310请求参数信息有误，
			311Key格式错误,
			306请求有护持信息请检查字符串,
			110请求来源未被授权
		 */
		String resultCode = JSONUtil.getByPath(jsonObj, "status").toString();
		
		String address = "";
		if(resultCode == "0") {
			// 纬度
			//String lat = (String) JSONUtil.getByPath(jsonObj, "result.location.lat");
			// 经度
			//String lng = (String) JSONUtil.getByPath(jsonObj, "result.location.lng");
			// 国家
			String nation = (String) JSONUtil.getByPath(jsonObj, "result.ad_info.nation");
			// 省
			String province = (String) JSONUtil.getByPath(jsonObj, "result.ad_info.province");
			// 市
			String city = (String) JSONUtil.getByPath(jsonObj, "result.ad_info.city");
			// 区
			String district = (String) JSONUtil.getByPath(jsonObj, "result.ad_info.district");
			// 行政区划代码
			//String adcode = JSONUtil.getByPath(jsonObj, "result.ad_info.adcode").toString();
			address = nation + province + city + district;
			System.out.println(address);
			return address;
		} else {
			// log.error("ip{}获取地理位置异常 ，响应码是{}", ip, resultCode);
			return address;
		}
	}
}
